package com.wyd.component.netty.handler;

import com.wyd.component.netty.constants.ChannelKey;
import com.wyd.component.netty.constants.Constants;
import com.wyd.component.netty.message.HeartBeatReq;
import com.wyd.utils.SeqUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        ChannelKey channelKey = ctx.channel().attr(Constants.attriKey).get();
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idle = (IdleStateEvent) evt;
            if (idle.state() == IdleState.ALL_IDLE ) {
                //长时间没有读写，直接关闭channel
                try {
                    ctx.channel().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                log.error("长时间无读写，关闭channel===>{}", channelKey==null?"未知":channelKey.getCardId());
            }
            if (idle.state() == IdleState.READER_IDLE) {
                HeartBeatReq req=new HeartBeatReq();
                req.setSeqId(SeqUtil.getId());
                req.setCreateTime(new Date());
                req.setCardId(channelKey.getCardId());
                ctx.channel().writeAndFlush(req);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
